const http = require("http")
const fs = require("fs")
const qs = require("querystring");
const { registry } = require("gulp");

http.createServer((req, res) => {
    if (req.url.includes("/api")) {
        dataRequire(req, res);
    } else {
        fileRequire(req, res);
    }
}).listen(3000, () => {
    console.log("服务器开启成功，地址为：http://localhost:3000")
})

// 注册接口
// http://localhost:3000/api?

function dataRequire(req, res) {
    let str = "";
    req.on("data", (chunk) => {
        str += chunk;
    })
    req.on("end", () => {
        let data;
        if (str) {
            data = qs.parse(str);
        } else {
            const urlObj = new URL("http://localhost:3000" + req.url);
            data = qs.parse(urlObj.search.slice(1));
        }
        // 1. 过滤前端请求，判断请求功能
        switch (data.type) {
            case "getGoods":
                // 获取数据
                getGoods(req, res); break;
            // 注册
            case "register":
                register(req, res, data); break;
            // 登录
            case "login":
                login(req, res, data); break;
        }
    })
}

// 模拟数据库存储用户信息
// const userMsg = [{ username: "admin", password: 123 }];
const userMsg = []
// 注册功能
function register(req, res, data) {
    // 注册只有用户名重复的失败
    const flag = userMsg.some(val => val.username === data.username)
    const obj = {};
    if (flag) {
        // 用户名重复
        obj.code = 0,
            obj.title = "用户名重复",
            obj.data = "NOT DATA"
    } else {
        // 注册成功 ,添加用户信息
        userMsg.push({
            username: data.username,
            password: data.password,
        })
        console.log(userMsg);
        obj.code = 1,
            obj.title = "注册成功",
            obj.data = "NOT DATA"
    }
    // 返回信息
    res.write(JSON.stringify(obj))
    console.log("正在注册");
    res.end()
}

// 登录功能
function login(req, res, data) {
    // 1：验证用户名存不存在
    let i = 0;
    const flag = userMsg.some((val, idx) => val.username === data.username)
    const obj = {};
    if (flag) {
        // 密码是否正确
        if (userMsg[i].password === data.password) {
            // 登录成功
            obj.code = 1;
            obj.title = "登录成功";
            obj.data = data.username
        } else {
            // 密码不对
            obj.code = 0;
            obj.title = "密码错误";
            obj.data = "NOT DATA"
        }
    } else {
        // 账号不存在
        obj.code = 2;
        obj.title = "用户名不存在";
        obj.data = "NOT DATA"
    }
    res.write(JSON.stringify(obj))
    console.log("正在登录");
    res.end()
}

function getGoods(req, res, data) {
    fs.readFile("./data/getPro.json", (err, data) => {
        res.write(data);
        res.end();
    })
}

function fileRequire(req, res) {
    fs.readFile("./www" + req.url.split("?")[0], (err, data) => {
        if (err) {
            res.write("404");
        } else {
            res.write(data);
        }
        res.end();
    })
}
